/*
 * @ProjectName: 编程学习
 * @Copyright:   2019 HangZhou Yi Dev, Ltd. All Right Reserved.
 * @address:     https://yiyuery.github.io/
 * @date:        2019/5/20 20:57
 * @email:       xiazhaoyang@live.com
 * @description: 本内容仅限于编程技术学习使用，转发请注明出处.
 */
package com.yi.yier.boot.autoconfigure.codegenerator.api.validation;

import com.yi.yier.boot.autoconfigure.codegenerator.api.exception.ValidationException;
import com.yi.yier.boot.autoconfigure.codegenerator.api.exception.code.ApiErrorCode;
import lombok.extern.slf4j.Slf4j;

import java.util.function.Function;

/**
 * <p>
 *
 * </p>
 *
 * @author Yi
 * @version v1.0.0
 * @date 2019-07-06 19:52
 * @modificationHistory=========================逻辑或功能性重大变更记录
 * @modify By: {修改人} 2019-07-06
 * @modify reason: {方法名}:{原因}
 * ...
 */
@Slf4j
public class ValidateUtil {

    /**
     * 条件满足返回异常
     * @param condition
     * @param errorMessage
     * @param <T>
     */
    public static <T> void requireSatisfyThrowException(Boolean condition,String errorMessage){
        if(condition){
            log.error(String.format("ValidateUtil.requireNotSatisfyThrowException failed: %s",errorMessage));
            throw new ValidationException(ApiErrorCode.CONDITION_NOT_SATISFY_ERROR.getCode());
        }
    }

    /**
     * 条件不满足向上层抛出异常
     * @param func
     * @param t
     * @return
     */
    public static <T> T requireNotSatisfyThrowException(Function<T,? extends Boolean> func, T t){
        if(!func.apply(t)){
            log.error("ValidateUtil.requireNotSatisfyThrowException failed");
            throw new ValidationException(ApiErrorCode.CONDITION_NOT_SATISFY_ERROR.getCode());
        }
        return t;
    }

    /**
     * 校验返回自定义信息
     * @param func
     * @param t
     * @param <T>
     * @return
     */
    public static <T> T requireNotSatisfyThrowException(Function<T,? extends Boolean> func, T t,String errorMessage){
        if(!func.apply(t)){
            log.error(String.format("ValidateUtil.requireNotSatisfyThrowException failed: %s",errorMessage));
            throw new ValidationException(ApiErrorCode.CONDITION_NOT_SATISFY_ERROR.getCode(),errorMessage);
        }
        return t;
    }
}
